const connection = require("../app/database")

class MessagesService {
  // 查询留言
  async getMessageList(start, end) {
    const statement = `SELECT * FROM message;`
    const result = await connection.execute(statement)
    const res = result[0].sort((a, b) => b.id - a.id).slice(start, end)
    return res
  }
  // 查询留言数量
  async getDataNum() {
    const statement = `SELECT COUNT(*) total FROM message;`
    const [result] = await connection.execute(statement)
    const total = result[0].total
    return total
  }
  // 创建留言
  async setMessage(msg, timestamp) {
    const statement = `INSERT INTO message (msg, timestamp, user_id) VALUES (?, ?, ?);`
    const [result] = await connection.execute(statement, [msg, timestamp, 1])
    return result
  }

  // 删除留言
  async remove(messageId) {
    const statement = `DELETE FROM message WHERE id = ?;`
    const [result] = await connection.execute(statement, [messageId])
    return result
  }

  // 查询所有留言
  async list() {
    const statement = `SELECT * FROM message;`
    const [result] = await connection.execute(statement)
    return result
  }
}

module.exports = new MessagesService()